/**
 * Created by John on 2016/7/13.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        pageResults(collection, 0);
    });
});

function pageResults(collection, skip) {
    var query = {first: 'w'};
    var cursor = collection.find(query);
    var limit = 3;
    cursor.skip(skip).limit(limit);
    var pageStart = skip + 1;
    var pageEnd = pageStart + limit - 1;
    var more = skip < 8;
    var msg = 'Page ' + pageStart + ' to ' + pageEnd;
    msg += ' skip: ' + skip;
    console.log(msg);
    displayCursor(cursor, pageResults, collection, pageEnd, more);
}

function displayCursor(cursor, callback, collection, skip, more) {
    cursor.toArray(function (err, items) {
        var wordStr = '';
        for (var i in items) {
            wordStr += items[i].word + ',';
        }
        if (wordStr.length > 23) {
            wordStr = wordStr.slice(0, 23) + '...';
        }
        console.log(wordStr);
        if (more) {
            callback(collection, skip++);
        } else {
            myDB.close();
        }
    });
}